import { Router } from "../../utils/common.js";
Page({

  data: {
    isLogin: false
  },

  onShow: function () {
    // 判断用户是否登录
    let isLogin = wx.getStorageSync('isLogin');
    this.setData({
      isLogin: isLogin
    })
  },

  bindGetUserInfo: function (e) {
    // 获取当前年月日
    var date = new Date();
    var myDate = date.toLocaleDateString(); //获取当前日期
    if (e.detail.userInfo) {
      const db = wx.cloud.database();
      db.collection('p_user').where({
        _openid: wx.getStorageSync('openid')
      }).get({
        success: res => {
          if (res.data.length > 0) {
            wx.setStorageSync('isLogin', true);
            this.setData({
              isLogin: true
            })
          } else {
            var user = {
              nickName: e.detail.userInfo.nickName,
              avatarUrl: e.detail.userInfo.avatarUrl,
              province: e.detail.userInfo.province,
              city: e.detail.userInfo.city,
              openid: wx.getStorageSync('openid'),
              gender: e.detail.userInfo.gender,
              step: 10000, // 微信步数
              stepRemain: 0, // 剩余步数
              feedTimes: 0, // 已遛狗次数
              totalStep:0, //总遛狗距离
              createTime: this.getNextDate(myDate, 0), // 创建日期
              modifyTime: this.getNextDate(myDate, -1) // 更新日期
            }
            //授权成功未注册用户保存用户信息
            const db = wx.cloud.database();
            db.collection('p_user').add({
              // data 字段表示需新增的 JSON 数据
              data: user
            }).then(res => {
              wx.setStorageSync('isLogin', true);
              this.setData({
                isLogin: true
              });
                wx.showToast({
                  title: "注册成功",
                  duration: 2000,
                })
            })
          }
        },
        fail: err => {
          wx.setStorageSync('isLogin', false);
          console.log('[数据库] [查询记录] 失败：')
        }
      })

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '同意授权啦小火鸡!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },

  getNextDate(date, day) {
    var dd = new Date(date);
    dd.setDate(dd.getDate() + day);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return y + "-" + m + "-" + d;
  },

  navToPetEdit: function () {
    Router.navigateTo("../dogedit/dogedit");
  }

})